from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core import serializers
import requests
import json

from myapp.models import Book


# Create your views here.
@require_http_methods(["POST"])
def add_book(request):
    response = {}
    try:
        if request.method == 'POST':
            # book = Book(book_name=request.GET.get('book_name'))
            book = Book(book_name=json.loads(request.body)['parms'])
            # print(json.loads(request.body)['parms'])
            book.save()
            response['msg'] = 'success'
            response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)


@require_http_methods(["GET"])
def show_books(request):
    response = {}
    try:
        books = Book.objects.filter()
        response['list'] = json.loads(serializers.serialize("json", books))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)
